package com.macro.mall.uitls;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.macro.mall.config.ApiConfig;
import com.macro.mall.model.UmsMemberReceiveAddress;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author：MinxiaoHao
 * @Description:
 * @name：AddreInfoUtils
 * @Date：2024/10/22 22:26
 */
@Component
public class AddressInfoUtils {
    @Autowired
    private ApiConfig apiConfig;

    public UmsMemberReceiveAddress getAddressInfo(String address){
        UmsMemberReceiveAddress umsMemberReceiveAddress = new UmsMemberReceiveAddress();
        String host = apiConfig.getHost();
        String path = apiConfig.getPath();
        String method = apiConfig.getMethod();
        String appcode = apiConfig.getAppcode();
        Map<String, String> headers = new HashMap<String, String>();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105

        headers.put("Authorization", "APPCODE " + appcode);
        //根据API的要求，定义相对应的Content-Type
        headers.put("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
        Map<String, String> querys = new HashMap<String, String>();
        Map<String, String> bodys = new HashMap<String, String>();
        bodys.put("address", address);


        try {
            HttpResponse response = HttpUtils.doPost(host, path, method, headers, querys, bodys);
            System.out.println(response.toString());
            String s = EntityUtils.toString(response.getEntity());
            JSONObject jsonObject = JSON.parseObject(s);
            Integer code = jsonObject.getInteger("code");
            if(code==200){
                JSONObject data = jsonObject.getJSONObject("data");
                if(data!=null){
                    umsMemberReceiveAddress.setDetailAddress(data.getString("detail"));
                    umsMemberReceiveAddress.setCity(data.getString("city"));
                    umsMemberReceiveAddress.setProvince(data.getString("province"));
                    umsMemberReceiveAddress.setRegion(data.getString("area"));
                    umsMemberReceiveAddress.setPostCode(data.getString("zipCode"));
                    umsMemberReceiveAddress.setName(data.getString("name"));
                    umsMemberReceiveAddress.setPhoneNumber(data.getString("mobile"));
                    return umsMemberReceiveAddress;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
